<template>

  <div class="card" style="height: 80vh">
     <div  class="font-semibold text-xl mb-4">工具库</div>
    <div :class="!isMobile ? 'flex': ''">
      <Button v-if="!isMobile" icon="pi pi-plus" @click="() => refEditor.visible()"/>
      <InputText placeholder="搜索" :class="!isMobile ? 'ml-2' : 'w-full'"
                 @keyup.enter.native="(e) => run({page:1, page_size: 30, tool_name: e.target.value})"/>
      <IconField iconPosition="left" :class="isMobile ? 'mt-3' : 'ml-2'">
        <SelectButton v-model="tagState.index"
                      :options="tagState.options"
                      aria-labelledby="basic"
                      style=" white-space: normal;"
                      @change="(e) =>run({page:1, page_size: 30, tags: tagState.index === '全部' ? '' : tagState.index})">

          <template #option="{option, index}">
            <div>
              {{ option }}
            </div>

          </template>
        </SelectButton>
      </IconField>
    </div>

    <DataView :value="data" :layout="layout" :loading="dataLoading" class="mt-3">
      <template v-if="!isMobile" #header>

        <div class="flex items-center justify-between">
          <div class="flex items-center ">
            最近：
            <div class="mr-3 underline text-blue-500 cursor-pointer" v-for="item in latelyList"
                 @click="showRun(item.tool_id)">{{ item.tool_name }}
            </div>
          </div>
          <SelectButton v-model="layout" :options="options" :allowEmpty="false">
            <template #option="{ option }">
              <i :class="[option === 'list' ? 'pi pi-bars' : 'pi pi-th-large']"/>
            </template>
          </SelectButton>
        </div>
      </template>

      <template #list="slotProps">
        <DataTable :value="slotProps.items" scrollable scrollHeight="60vh">
          <Column field="name" header="脚本名称"></Column>
          <Column field="type" header="类型">
            <template #body="slotProps">
              <Tag v-if="slotProps.data.type === 1" severity="info">SHELL</Tag>
              <Tag v-else-if="slotProps.data.type === 2" severity="info">PYTHON</Tag>
              <Tag v-else>未知</Tag>
            </template>
          </Column>
          <Column field="tags" header="标签"></Column>
          <Column field="username" header="创建者"></Column>
          <Column header="厉史记录">
            <template #body="slotProps">
              <a class="cursor-pointer"
                 @click=" (e) =>{e.stopPropagation();router.push({path: '/toolkit/history-log/', query: {_id: slotProps.data.id}})}">查看</a>
            </template>
          </Column>
          <Column field="m_time" header="更新时间">
            <template #body="slotProps">
              {{ formatDate(slotProps.data.m_time) }}
            </template>
          </Column>
          <Column header="运行">
            <template #body="slotProps">
              <Button icon="pi pi-play-circle" severity="success" rounded text size="large"
                      @click=" (e) =>{e.stopPropagation();showRun(slotProps.data.id)}"/>
              <!--              <a class="cursor-pointer"-->
              <!--                 @click=" (e) =>{e.stopPropagation();router.push({path: '/toolkit/history-log/', query: {_id: slotProps.data.id}})}">查看</a>-->
            </template>
          </Column>
        </DataTable>
        <!--        <ScrollPanel style="width: 100%; height: 63vh">-->
        <!--          <div class="grid gap-4">-->
        <!--            <div v-for="(item, index) in slotProps.items" :key="index" class="col-span-12 cursor-pointer"-->
        <!--                 @click="() => router.push({name: 'preview', query: {id: item.id}})">-->
        <!--              <div class="flex flex-col sm:flex-row sm:items-center p-4 gap-3 border-t border-gray-200">-->
        <!--                <div>-->
        <!--                  <img v-if="item.type === 1" :src='bashIco' class="h-8 w-8 rounded" alt="Bash Icon">-->
        <!--                  <img v-if="item.type === 2" :src='pythonIco' class="h-8 w-8 mx-auto rounded"-->
        <!--                       alt="Python Icon">-->
        <!--                </div>-->
        <!--                <div class="flex flex-col md:flex-row justify-between md:items-center flex-1 gap-4">-->
        <!--                  <div class="flex flex-row md:flex-col justify-between items-start gap-2">-->
        <!--                    <div>-->
        <!--                      <div class="text-lg font-medium text-gray-900 mt-2">{{ item.name }}</div>-->
        <!--                    </div>-->
        <!--                    <div class="bg-gray-100 mt-1 p-2 rounded">-->
        <!--                      <div class="flex items-center justify-center">-->
        <!--                                                <span class="font-medium text-secondary text-sm mr-2">{{-->
        <!--                                                    item.tags-->
        <!--                                                  }}</span>-->
        <!--                        {{ item.desc }}-->
        <!--                      </div>-->
        <!--                    </div>-->
        <!--                  </div>-->
        <!--                  <div>-->
        <!--                    <span class="text-xl font-semibold text-gray-900">{{ item.username }}</span>-->
        <!--                  </div>-->
        <!--                  <div class="flex flex-col md:items-end gap-5">-->
        <!--                    <div class="flex flex-row-reverse md:flex-row gap-2">-->
        <!--                      <Button icon="pi pi-play-circle" rounded-->
        <!--                              @click="(e) => { e.stopPropagation(); showRun(item.id) }"/>-->
        <!--                    </div>-->
        <!--                  </div>-->
        <!--                </div>-->
        <!--              </div>-->
        <!--            </div>-->
        <!--          </div>-->

        <!--        </ScrollPanel>-->
      </template>

      <template #grid="slotProps">
<!--       <div v-if="dataLoading" class="grid sm:grid-cols-1 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 gap-3 mt-3" >-->
<!--          <div v-for="_ in 50" class='surface-card rounded pt-3 pb-3  flex flex-col items-center gap-2 border border-surface-100'>-->
<!--            <Skeleton size="4rem" shape="circle" class="!bg-surface-100"/>-->
<!--            <Skeleton height="1rem" width="6rem" class="!bg-surface-100"/>-->
<!--            <Skeleton height="1rem" width="6rem" class="!bg-surface-100"/>-->
<!--          </div>-->
<!--        </div>-->

        <ScrollPanel style="width: 100%; height: 63vh">
          <div class="grid sm:grid-cols-1 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6" id='move'>
            <div v-for="(item, index) in slotProps.items" :key="index"
                 class="p-2">

              <div class='relative surface-card rounded pt-3 pb-3 hover-box flex flex-col items-center'
                   id='move-parent'
                   @click="() => router.push({name: 'preview', query: {id: item.id}})">
                <div class="move-icon drag-handle absolute top-1 right-1 h-4 w-5"></div>

                <!--                <div v-if="!isMobile" class="w-full flex justify-end">-->
                <!--                  <i class="pi pi-bars move-icon drag-handle"-->
                <!--                     style="font-size: 1rem" @click=" (e) =>{e.stopPropagation();}"></i>-->
                <!--                </div>-->

                <img v-if="item.type === 1" :src='bashIco' height="30px" width="30px" class="m-2">
                <img v-if="item.type === 2" :src='pythonIco' height="30px" width="30px" class="m-2">
                <div class='flex align-items-center m-2'>
                  <div style="word-break: break-all;height: 1rem">{{ item.name }}</div>
                </div>
                <div>

                  <Button icon="pi pi-play-circle" severity="success" rounded text size="large"
                          @click=" (e) =>{e.stopPropagation();showRun(item.id)}"/>
                  <Button icon="pi pi-history" severity="secondary" text rounded
                          @click=" (e) =>{e.stopPropagation();router.push({path: '/toolkit/history-log/', query: {_id: item.id}})}"/>
                </div>
              </div>

            </div>
          </div>
        </ScrollPanel>
      </template>
    </DataView>
  </div>
  <RunTool ref="refRun"></RunTool>
  <editor ref="refEditor" @refresh="refresh"></editor>
</template>

<script setup>
import {ref, reactive, nextTick, computed} from "vue";
import {useRequest} from 'ahooks-vue';
import {ApiGetTags, ApiToolkitList, ApiSort, ApiLately} from "@/api/toolkit.js";
import IconField from 'primevue/iconfield';
import pythonIco from '@/assets/python.png'
import bashIco from '@/assets/bash.ico'
import {useToast} from "primevue/usetoast";
import RunTool from "@/views/toolkit/RunTool.vue";
import editor from "@/views/toolkit/editor.vue";
import router from "@/router.js";
import Sortable from 'sortablejs'
import ScrollPanel from 'primevue/scrollpanel';
import VirtualScroller from 'primevue/virtualscroller';
import {formatDate} from "@/utils/format.js";

const isMobile = ref(window.innerWidth < 768);
const toast = useToast();

const refRun = ref();
const refEditor = ref();
const options = ref(['list', 'grid']);

const data = ref()
const tagState = reactive({
  index: '全部',
  options: ['全部']
});

const visible = reactive({
  createModal: false
})

const {data: toolkitData, loading: dataLoading, run, refresh} = useRequest(ApiToolkitList, {
  defaultParams: [{
    page: 1,
    page_size: 30
  }],
  onSuccess: (e) => {
    data.value = e.data.list;
    nextTick(() => {
      const el = document.getElementById('move')
      new Sortable(el, {
        animation: 150,
        // 拖拽时预览图样式
        ghostClass: 'sortable-ghost',
        handle: '.drag-handle',
        // 拖拽结束
        onEnd: async (evt) => {
          if (evt.oldIndex !== evt.newIndex) {
            const newData = JSON.parse(JSON.stringify(data.value))
            // 通过index更改数据，获取拖拽排序之后的数据
            const changeData = newData.splice(evt.oldIndex, 1); // 移除旧位置的元素
            newData.splice(evt.newIndex, 0, changeData[0]); // 插入到新位置
            const ids = newData.map(item => item.id)
            // 打印排序后的新数据
            const result = await ApiSort({ids: ids})
            if (result.code !== 0) {
              toast.add({severity: 'error', summary: '错误', detail: result.msg, life: 3000});
            }
          }
        }
      })
    })
  }
})

// data
const {data: tagsData, loading: tagsLoading} = useRequest(ApiGetTags, {onSuccess: initTags})
const {data: latelyData} = useRequest(ApiLately)
const latelyList = computed(() => latelyData.value?.data.list || []);

console.log('123', latelyList)

function initTags(data) {
  data.data.list.forEach((item, index) => {
    if (item && item !== 'null')
      tagState.options.push(item.split(":")[0])
  })
}

const layout = ref('grid');

const getSeverity = (product) => {
  switch (product.inventoryStatus) {
    case 'INSTOCK':
      return 'success';

    case 'LOWSTOCK':
      return 'warning';

    case 'OUTOFSTOCK':
      return 'danger';

    default:
      return null;
  }
}


function showRun(id) {
  console.log(data)
  refRun.value.show(id)
}

</script>

<style scoped>
.p-selectbutton {
  display: block;
}
</style>
